package avicit.bdp.dms.tdm.rest;

import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.tdm.dto.BdpAssetCatalogDTO;
import avicit.bdp.dms.tdm.service.BdpAssetCatalogService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.JsonHelper;
import avicit.platform6.commons.utils.StringUtils;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.domain.VueNode;
import avicit.platform6.core.rest.msg.QueryReqBean;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/** 数据资产数据目录Rest */
@RestController
@Api(tags = "数据资产数据目录")
@RequestMapping("/api/bdp/dms/catalog")
public class BdpAssetCatalogRest {

  @Autowired private BdpAssetCatalogService bdpAssetCatalogService;

  @Autowired private ConvertColumnClient convertColumnClient;

  /**
   * 加载树
   *
   * @param level 树的等级
   * @param id 父节点ID
   */
  @GetMapping("/get-tree/{level}/{id}/v1")
  @ApiOperation(value = "加载树")
  public ResponseMsg<List<VueNode>> getTree(
      @ApiParam(value = "展开的树的层级", name = "level") @PathVariable("level") int level,
      @ApiParam(value = "父节点ID", name = "id") @PathVariable("id") String id) {
    ResponseMsg<List<VueNode>> responseMsg = new ResponseMsg<>();
    if (id == null) {
      id = "-1";
    }
    if (level == 0) {
      level = 1;
    }
    String orgIdentity = ThreadContextHelper.getOrgId();
    responseMsg.setResponseBody(bdpAssetCatalogService.getTreeByParentId(id, level, orgIdentity));
    return responseMsg;
  }

  /**
   * 加载树（只获取有效的数据）
   *
   * @param level 树的等级
   * @param id 父节点ID
   */
  @GetMapping("/get-valid-tree/{level}/{id}/v1")
  @ApiOperation(value = "加载树")
  public ResponseMsg<List<VueNode>> getEmpowerTree(
      @ApiParam(value = "展开的树的层级", name = "level") @PathVariable("level") int level,
      @ApiParam(value = "父节点ID", name = "id") @PathVariable("id") String id) {
    ResponseMsg<List<VueNode>> responseMsg = new ResponseMsg<>();
    if (id == null) {
      id = "-1";
    }
    if (level == 0) {
      level = 1;
    }
    String orgIdentity = ThreadContextHelper.getOrgId();
    responseMsg.setResponseBody(
        bdpAssetCatalogService.getValidTreeByParentId(id, level, orgIdentity));
    return responseMsg;
  }

  /** 加载树（获取授权数据） */
  @GetMapping("/get-auth-tree/v1")
  @ApiOperation(value = "加载树(获取授权数据)")
  public ResponseMsg<List<VueNode>> getAuthValidTree() {
    ResponseMsg<List<VueNode>> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpAssetCatalogService.getTreeAuthValidTree());
    return responseMsg;
  }

  /**
   * 启用/停用
   *
   * @param dto 修改对象
   */
  @PutMapping("/on-off/v1")
  @ApiOperation(value = "启用/停用数据")
  public ResponseMsg<Integer> updateDataStatus(@RequestBody BdpAssetCatalogDTO dto) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    BdpAssetCatalogDTO dtoById = bdpAssetCatalogService.queryById(dto.getId());
    dtoById.setStatus(dto.getStatus());
    responseMsg.setResponseBody(bdpAssetCatalogService.updateDataStatus(dtoById));
    return responseMsg;
  }

  /*
   * 按条件分页查询
   *
   * @param queryReqBean 查询条件
   */
  @PostMapping("/search-by-page/v1")
  @ApiOperation(value = "按条件分页查询")
  public ResponseMsg<QueryRespBean<BdpAssetCatalogDTO>> searchByPage(
      @ApiParam(value = "查询条件", name = "queryReqBean") @RequestBody
          QueryReqBean<BdpAssetCatalogDTO> queryReqBean) {
    ResponseMsg<QueryRespBean<BdpAssetCatalogDTO>> responseMsg = new ResponseMsg<>();
    if (StringUtils.isNotEmpty(queryReqBean.getSidx())
        && StringUtils.isNotEmpty(queryReqBean.getSord())) {
      String sortExp =
          BusinessUtil.getSortExpColumnName(
              queryReqBean.getSidx(), queryReqBean.getSord(), BdpAssetCatalogDTO.class);
      if (StringUtils.isNotEmpty(sortExp)) {
        queryReqBean.setSortExp(sortExp);
      }
    }
    if (StringUtils.isNotEmpty(queryReqBean.getKeyWord())) {
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      BdpAssetCatalogDTO searchKeyWordParam =
          JsonHelper.getInstance()
              .readValue(
                  queryReqBean.getKeyWord(),
                  dateFormat,
                  new TypeReference<BdpAssetCatalogDTO>() {});
      queryReqBean.setSearchParams(searchKeyWordParam);
    }
    // 文档密级
    String wordSecret = ThreadContextHelper.getWordSecret();
    QueryRespBean<BdpAssetCatalogDTO> result =
        bdpAssetCatalogService.searchByPage(
            queryReqBean, ThreadContextHelper.getOrgId(), wordSecret, queryReqBean.getSortExp());
    valueConvert(result.getResult());
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /** 初始化根节点 如果需要修改根节点数据通过前台页面设置 */
  @PostMapping("/insert-root/v1")
  @ApiOperation(value = "初始化根节点  如果需要修改根节点数据通过前台页面设置")
  public ResponseMsg<String> insertRoot() {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    BdpAssetCatalogDTO tree = new BdpAssetCatalogDTO();
    tree.setParentId("-1");
    tree.setOrgIdentity(ThreadContextHelper.getOrgId());
    tree.setStatus("1");
    tree.setClassifyName("资产目录");
    tree.setSecretLevel("1");
    tree.setTreePath("-1");
    tree.setTreeSort(1L);
    responseMsg.setResponseBody(bdpAssetCatalogService.insert(tree));
    return responseMsg;
  }

  /**
   * 新增树对象
   *
   * @param dto 插入对象
   */
  @PostMapping("/save/v1")
  @ApiOperation(value = "新增树对象")
  public ResponseMsg<BdpAssetCatalogDTO> save(
      @ApiParam(value = "插入对象", name = "dto") @RequestBody BdpAssetCatalogDTO dto) {
    ResponseMsg<BdpAssetCatalogDTO> responseMsg = new ResponseMsg<>();
    if (StringUtils.isEmpty(dto.getId())) {
      dto.setOrgIdentity(ThreadContextHelper.getOrgId());
      bdpAssetCatalogService.insert(dto);
    } else {
      bdpAssetCatalogService.update(dto);
    }
    responseMsg.setResponseBody(dto);
    return responseMsg;
  }

  /**
   * 通过主键获取单条记录
   *
   * @param id 主键id
   */
  @GetMapping("/get/{id}/v1")
  @ApiOperation(value = "通过树主键获取单条记录")
  public ResponseMsg<BdpAssetCatalogDTO> queryById(
      @ApiParam(value = "主键id", name = "id") @PathVariable("id") String id) {
    ResponseMsg<BdpAssetCatalogDTO> responseMsg = new ResponseMsg<>();
    BdpAssetCatalogDTO dto = bdpAssetCatalogService.queryById(id);
    if (dto != null) {
      valueConvert(Collections.singletonList(dto));
    }
    responseMsg.setResponseBody(dto);
    return responseMsg;
  }

  /**
   * 加载至指定节点
   *
   * @param id id
   */
  @GetMapping("/expand-tree/{id}/v1")
  @ApiOperation(value = "加载至指定节点")
  public ResponseMsg<List<VueNode>> expandById(
      @ApiParam(value = "主键id", name = "id") @PathVariable("id") String id) {
    ResponseMsg<List<VueNode>> responseMsg = new ResponseMsg<>();
    List<VueNode> vueNodes = bdpAssetCatalogService.expandById(id);
    responseMsg.setResponseBody(vueNodes);
    return responseMsg;
  }

  /**
   * 按树主键单条删除
   *
   * @param id 主键id
   */
  @DeleteMapping("/delete-by-id/{id}/v1")
  @ApiOperation(value = "批量删除")
  public ResponseMsg<Integer> deleteById(
      @ApiParam(value = "主键id", name = "id") @PathVariable("id") String id) throws Exception {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpAssetCatalogService.deleteById(id));
    return responseMsg;
  }

  /**
   * 按树主键批量删除
   *
   * @param ids 逗号分隔的id串
   */
  @DeleteMapping("/delete-by-ids/{ids}/v1")
  @ApiOperation(value = "按树主键单条删除")
  public ResponseMsg<Integer> deleteByIds(
      @ApiParam(value = "主键id串", name = "ids") @PathVariable("ids") String ids) throws Exception {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpAssetCatalogService.deleteByIds(ids));
    return responseMsg;
  }

  /**
   * 获取新的treeSort值
   *
   * @param id 父节点ID
   */
  @GetMapping("/get-new-tree-sort/{id}/v1")
  @ApiOperation(value = "获取新的treeSort值")
  public ResponseMsg<Long> getNewTreeSortById(
      @ApiParam(value = "父节点ID", name = "id") @PathVariable String id) {
    ResponseMsg<Long> responseMsg = new ResponseMsg<>();
    Long newTreeSort = bdpAssetCatalogService.getNewTreeSortByParentId(id);
    responseMsg.setResponseBody(newTreeSort);
    return responseMsg;
  }

  /**
   * 唯一性校验接口
   *
   * @param queryReqBean 查询条件
   */
  @PostMapping("/uniqueCheck/v1")
  @ApiOperation(value = "唯一性校验接口")
  public ResponseMsg<List<BdpAssetCatalogDTO>> uniqueCheck(
      @ApiParam(value = "查询条件", name = "params") @RequestBody
          QueryReqBean<BdpAssetCatalogDTO> queryReqBean) {
    ResponseMsg<List<BdpAssetCatalogDTO>> responseMsg = new ResponseMsg<>();
    List<BdpAssetCatalogDTO> result = bdpAssetCatalogService.uniqueCheck(queryReqBean);
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /** 通过平台API将树字段值转换为名称，包括通用选择组件、通用代码 */
  private void valueConvert(List<BdpAssetCatalogDTO> list) {
    // 循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    for (BdpAssetCatalogDTO dto : list) {
      BusinessUtil.createConvertSet(
          convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel());
    }
    if (convertFormData.size() > 0) {
      // 获取请求结果
      Map<String, Map<String, String>> convertResultData =
          convertColumnClient.replace(convertFormData);
      // 循环设置Alias或Name的值
      for (BdpAssetCatalogDTO dto : list) {
        dto.setSecretLevelName(
            BusinessUtil.convertFormat(
                convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel()));
      }
    }
  }

  /** 下载模板 */
  @ApiOperation(value = "下载模板")
  @GetMapping("/downloadTemplate")
  public void downloadTemplate(HttpServletResponse response) throws Exception {
    bdpAssetCatalogService.downloadTemplate(response);
  }

  @ApiOperation(value = "导出")
  @ApiImplicitParams({
    @ApiImplicitParam(value = "父节点", name = "parentId", dataType = "String"),
    @ApiImplicitParam(value = "ID列表，逗号分割", name = "ids", dataType = "String")
  })
  @GetMapping("/export")
  public void export(
      @RequestParam(required = false, name = "parentId") String parentId,
      @RequestParam(required = false, name = "ids") String ids,
      HttpServletResponse response)
      throws Exception {

    bdpAssetCatalogService.export(parentId, ids, response);
  }

  @ApiOperation(value = "导入")
  @PostMapping("/import")
  public ResponseMsg<String> importAssetCatalog(@RequestParam(value = "file") MultipartFile file)
      throws Exception {

    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(bdpAssetCatalogService.importAssetCatalog(file));
    return responseMsg;
  }
}
